# -*- coding: utf-8 -*-

from odoo.http import request

from odoo_contrib import http as contrib_http
from odoo_contrib.parser import parse_with
from odoo_contrib.marshal import marshal_with

from ..schemas import parser
from ..schemas import marshals
from ..utils.settings import Settings
from ..utils.exceptions import FrontendException


@contrib_http.route('/exhibition')
class ArticleRepository(contrib_http.Controller):
    @contrib_http.route('/article/', methods=['GET'])
    @parse_with(parser.article.ArticleListSchema)
    @marshal_with(marshals.article.ArticleRepositorySchema, envelope='data')
    def article_list(self):
        params = self.parser.parse()
        page = params['page']
        page_size = Settings().page_size
        enabled_only = params['enabled_only']

        domains = []
        if enabled_only:
            domains.append(('enabled', '=', True))
        articles = request.env['exhibition.article'].search(
            domains,
            offset=page_size * page,
            limit=page_size,
        )
        return {
            'entries': articles,
            'count': request.env['exhibition.article'].search_count(domains),
        }


@contrib_http.route('/exhibition')
class ArticleEntry(contrib_http.Controller):
    @contrib_http.route('/article/entry/<int:aid>')
    @marshal_with(marshals.article.ArticleSchema, envelope='data')
    def article_entry(self, aid):
        article = request.env['exhibition.article'].browse(aid)
        if not article.exists():
            raise FrontendException(
                errcode=200201,
                params={
                    'articleId': aid,
                }
            )
        article.been_viewed()
        return article
